package com.udl.emailfs.system;

import java.rmi.AccessException;
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.udl.emailfs.service.EmailFDS;

public class RMIHandler {

    private int port;
    private EmailFDS rmiImpl;
    private Registry rmiRegistry;
    public Logger log;
    public String RMINAME;

    /**
     * Creates an RMI Handler object with port <code>pport</code> and peer <code>p</code>.
     * @param pport Number of port where to create the RMI registry.
     * @param p Peer that the registry will belong to.
     */
    
    public RMIHandler(String name, int pport) {
        RMINAME = name;
        port = pport;
        log=Logger.getLogger(name);
    }
    
    public RMIHandler() {
    }

    /**
     * Starts the RMI registry and binds the remote object.
     */
    public void start() {
        log.log(Level.INFO, "Starting RMI registry...");

        try {
            rmiImpl= new EmailFDS();
            rmiRegistry = LocateRegistry.getRegistry(port);
        } catch (RemoteException ex) {
            Logger.getLogger(RMIHandler.class.getName()).log(Level.SEVERE, null, ex);
        }


        try {
            rmiRegistry.list();
        } catch (RemoteException ex) {
            try {
                rmiRegistry = LocateRegistry.createRegistry(port);
            } catch (RemoteException ex1) {
                Logger.getLogger(RMIHandler.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }

        try {
            rmiRegistry.rebind(RMINAME, (Remote) rmiImpl);
        } catch (RemoteException ex) {
            Logger.getLogger(RMIHandler.class.getName()).log(Level.SEVERE, null, ex);
        }

        log.log(Level.INFO, "RMI registry STARTED.");
    }

    /**
     * Unbind the remote object.
     */
    public void stop() {
        try {
            log.log(Level.INFO, "Stopping RMI registry...");
            UnicastRemoteObject.unexportObject((Remote) rmiImpl, true);
            rmiRegistry.unbind(RMINAME);
            log.log(Level.INFO, "RMI registry STOPPED.");
        } catch (NotBoundException ex) {
            Logger.getLogger(RMIHandler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (AccessException ex) {
            Logger.getLogger(RMIHandler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (RemoteException ex) {
            log.log(Level.SEVERE, null, ex);
        }
    }
}

